package com.mars.designpatterns.proxy.cglib;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * author by: mars
 * Date: 2020/3/10 9:19
 * Description:
 */
public class HelloInterceptor implements MethodInterceptor {

    private Object object;

    public Object getObject() {
        return object;
    }

    public void setObject(Object object) {
        this.object = object;
    }

    public HelloInterceptor(Object object) {
        this.object = object;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        beforeMethod();
        // 第一个参数：代理的目标对象
        // 第二个参数：方法的入参
        Object ret = methodProxy.invoke(object,objects);
        afterMethod();
        return ret;
    }
    private void beforeMethod() {
        System.out.println("before code");
    }
    private void afterMethod() {
        System.out.println("after code");
    }

    public static void main(String[] args) {
        HelloServiceImpl hello = new HelloServiceImpl();
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(hello.getClass());
        enhancer.setCallback(new HelloInterceptor(hello));
        HelloServiceImpl imp = (HelloServiceImpl)enhancer.create();
        imp.sayHi("mars");
        imp.running(" world");
    }
}
